<template>
  <div>
    <div class="BuyMembers">
      <VipCard />
    </div>
    <div class="BuyMembers_main">
      <div class="buy_num">
        <p>购买数量:</p>
        <div class="buy_number">
          <span @click="handnumjian">-</span>
          <input v-model="number" type="number" @input="handleChecked" />
          <span @click="handnumjia">+</span>
        </div>
      </div>
      <div class="buy_shop">
        <p>支付类型：</p>
        <div class="buy_shopTitle">
          <div class="wechat">
            <div class="wechat_pay">
              <van-icon name="wechat-pay" />
            </div>
            <p>微信支付</p>
          </div>
          <div
            class="buy_shopradio"
            :class="checked === 1 ? ' BuyMembers_color' : ''"
            :name="checked"
            id="1"
          >
            <van-icon name="checked" />
          </div>
        </div>
      </div>

      <div class="buy-btn" @click="pay">
        确认支付<span style="color: #fdd586"
          >({{ priceFil(getPriceAll, 2) }})</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import VipCard from "@/components/VipCard";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      number: 1,
      checked: 1,
      priceAll: "",
      record: 0,
    };
  },
  components: { VipCard },
  created() {
    this.getVipPrice();
  },
  methods: {
    //获取vip价格
    getVipPrice() {
      let _self = this;
      this.$Api
        .getMetaByKey({
          key: "vipPrice",
        })
        .then((res) => {
          if (res.code == 1) {
            _self.priceAll = Number(res.data.value);
          }
        });
    },
    //支付创建订单
    pay() {
      let _self = this;
      let newDate = (new Date()).getTime()
      if((newDate - this.record) >= 2000){
        this.record = (new Date()).getTime()
        this.$Api
        .createVipOrder({
          num: this.number,
        })
        .then((res) => {
          if (res.code == 1) {
            _self.wxPay(res.data);
          }
        });
      }

    },
    onBridgeReady(data, orderNo) {
      const that = this;
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (res) {
          // let vConsole = new VConsole();
          console.log("微信支付返回值:");
          console.log(res);
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            let timer = setInterval(() => {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              // alert("get_brand_wcpay_request:ok");
              that.$Api
                .checkSuccess({ orderNo })
                .then((reslute) => {
                  if (reslute.code == 1 && reslute.data.state == 9) {
                    // this.$router.push('/me');
                    // setTimeout(() => {
                    // 	// window.history.go(-1);
                    that.$dialog
                      .alert({
                        title: "提示",
                        message: "支付成功，请前往个人中心复制激活码到学易知APP内激活。",
                      })
                      .then(() => {
                        that.$router.push("/personal_center");
                      });
                    clearInterval(timer);

                    // }, 500);
                  } else {
                    that.$dialog
                      .alert({
                        title: "提示",
                        message: "支付失败",
                      })
                      .then(() => {
                        that.$router.push("/members");
                      });
                    clearInterval(timer);
                  }
                })
                .catch((err) => {
                  that.$dialog
                    .alert({
                      title: "提示",
                      message: "支付失败",
                    })
                    .then(() => {
                      that.$router.push("/members");
                    });
                });
            }, 1000);
          } else {
            // that.$toast(res.err_msg);
          }
        }
      );
    },
    wxPay(orderNo) {
      let _self = this;
      this.$Api
        .pay({
          orderNo,
          payType: 3,
        })
        .then((res) => {
          if (res.code == 1) {
            if (res.data) {
              if (typeof window.WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                  document.addEventListener(
                    "WeixinJSBridgeReady",
                    this.onBridgeReady(res.data, orderNo),
                    false
                  );
                } else if (document.attachEvent) {
                  document.attachEvent(
                    "WeixinJSBridgeReady",
                    this.onBridgeReady(res.data, orderNo)
                  );
                  document.attachEvent(
                    "onWeixinJSBridgeReady",
                    this.onBridgeReady(res.data, orderNo)
                  );
                }
              } else {
                this.onBridgeReady(res.data, orderNo);
              }
              // this.onwx(payinfo)
            }
          }
        });
    },
    handleChecked() {
      if (this.number > 10001) {
        this.number = 10000;
      }
      if (this.number == NaN) {
        return;
      } else if (this.number == "" || this.number == 0) {
        this.number = 1;
      }
    },
    handnumjian() {
      if (this.number <= 1) return;
      this.number--;
    },
    handnumjia() {
      if (this.number >= 10000) return;
      this.number++;
    },
    priceFil: (data, num) => {
      //如果大多都是需要保留两位小数可以给一个默认值，这样就不用每次都传参数
      // if (!num) num = 2;
      return "￥" + data.toFixed(num);
    },
  },
  computed: {
    getPriceAll() {
      return this.number * this.priceAll;
    },
  },
};
</script>

<style scoped>
.BuyMembers_color {
  color: #ff9401;
}
.BuyMembers {
  border-bottom: 2px #f8f8f8 solid;
}
.BuyMembers_main {
  padding-bottom: 60px;
}
.BuyMembers_main .buy_num {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 31px 24px;
  border-bottom: 1px #eeeeee solid;
}
.BuyMembers_main .buy_num p {
  font-size: 28px;
  color: #444444;
}
.buy_number span {
  display: inline-block;
  width: 48px;
  height: 48px;
  line-height: 45px;
  border-radius: 100%;
  border: 1px #dcdcdc solid;
  text-align: center;
  vertical-align: middle;
}
.buy_number input {
  background: #f5f5f5;
  text-align: center;
  width: 122px;
  height: 60px;
  line-height: 60px;
  margin: 0 20px;
  border: none;
  border-radius: 10px;
  outline: none;
  font-size: 28px;
}
.buy_shop {
  padding: 31px 24px;
  box-sizing: border-box;
  margin-bottom: 82px;
}
.buy_shopTitle {
  margin-top: 38px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  vertical-align: middle;
}
.buy_shop .wechat {
  display: flex;
  justify-content: space-between;
  align-items: center;
  vertical-align: middle;
}
.buy_shop .wechat_pay {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  background: #2fb844;
  color: #fff;
  font-size: 64px;
  border-radius: 10px;
  margin-right: 23px;
}
.buy_shopradio {
  font-size: 36px;
}
.buy-btn {
  width: 680px;
  margin: 0 auto;
  height: 95px;
  text-align: center;
  line-height: 85px;
  background: linear-gradient(147deg, #ff9600 0%, #ff680c 100%);
  border-radius: 50px;
  border: 5px #ffcc00 solid;
  box-sizing: border-box;
  color: #fff;
}
</style>